package salve;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import messageHandler.ChangeStatusMessageHandler;
import messageHandler.LogInMessageHandler;
import messageHandler.SendBuzzMessageHandler;
import messageHandler.SendTextMessageHandler;

import org.openymsg.network.Session;

import core.MessageBuilder;
import core.MessageType;
import core.ReaderThread;
import core.WriterThread;

public class SlaveClient implements Runnable {

	private Socket socket;
	private OutputStream out;
	private InputStream in;
	private boolean isRunning;
	private Session session;
	private YahooSessionListener sessionListener;
	private ReaderThread reader;
	private WriterThread writerThread;

	public SlaveClient(Socket socket) {
		try {
			this.socket = socket;
			in = this.socket.getInputStream();
			out = this.socket.getOutputStream();
			isRunning = true;
			session = new Session();
			reader = new ReaderThread(in);
			writerThread = new WriterThread(out);
			sessionListener = new YahooSessionListener(writerThread);
			session.addSessionListener(sessionListener);
			new Thread(this).start();
		} catch (Exception e) {
			
		}		
	}
	
	@Override
	public void run() {
		while (isRunning){
			if (reader.queues.size()>0){
				String message = reader.queues.remove(0);
				ProcessMessage(message);
			}
		}
	}

	public void ProcessMessage(String message) {
        if (message.startsWith(MessageType.LogIn)) {        	
        	ProcessLogin(message);
        } else if (message.startsWith(MessageType.SendText)){
        	new SendTextMessageHandler().Process(message, session);
        } else if (message.startsWith(MessageType.SendBuzz)){
        	new SendBuzzMessageHandler().Process(message, session);
        } else if (message.startsWith(MessageType.ChangeStatus)){
        	new ChangeStatusMessageHandler().Process(message, session);
        }
    }
	
	public void ProcessLogin(String message) {
		boolean result = (Boolean) new LogInMessageHandler().Process(message, session);
		writerThread.QueueMessage(MessageBuilder.BuildLogInResult(result));
	}
}
